package cn.ticsmyc.tools.multiThread.serialThreadconfinement;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author Ticsmyc
 * @date 2021-06-03 16:06
 */
public abstract class AbstractSerializer<T, V> {

    private final TerminatableWorkerThread<T, V> workerThread;

    public AbstractSerializer(BlockingQueue<Runnable> blockingQueue, TaskProcessor<T, V> taskProcessor) {
        this.workerThread = new TerminatableWorkerThread<>(blockingQueue, taskProcessor);
    }


    /**
     * 对外暴露的执行方法
     *
     * @param params
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     */
    protected Future<T> service(Object... params) throws InterruptedException, ExecutionException {
        V task = getTaskParam(params);
        return workerThread.submit(task);
    }

    /**
     * 用于根据指定参数生成任务实例
     *
     * @param params
     * @return
     */
    protected abstract V getTaskParam(Object[] params);

    /**
     * 启动处理
     */
    public void init() {
        workerThread.start();
    }

    /**
     * 停止处理
     */
    public void shutdown() {
        workerThread.terminate();
    }

}
